//
//  CRInputToolBar.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/8/3.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "CRInputToolBar.h"
#import "UIImage+CRKit.h"

@interface CRInputToolBar()<ProxyTextViewDelegate>

proCopy NSArray<NSNumber *> *types;//支持的类型
proCopy NSDictionary *typeViewDict;//类型对应的视图

proAssign CRInputStatus status;//当前状态

@end

@implementation CRInputToolBar

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp {
    
    [self setBackgroundColor:[UIColor whiteColor]];
    
    self.voiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.voiceButton setImage:[UIImage cr_imageInKit:@"icon_toolview_voice_normal"] forState:UIControlStateNormal];
    [self.voiceButton setImage:[UIImage cr_imageInKit:@"icon_toolview_voice_pressed"] forState:UIControlStateHighlighted];
    [self.voiceButton sizeToFit];
    
    self.emoticonBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.emoticonBtn setImage:[UIImage cr_imageInKit:@"icon_toolview_emotion_normal"] forState:UIControlStateNormal];
    [self.emoticonBtn setImage:[UIImage cr_imageInKit:@"icon_toolview_emotion_pressed"] forState:UIControlStateHighlighted];
    [self.emoticonBtn sizeToFit];
    
    self.moreMediaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.moreMediaBtn setImage:[UIImage cr_imageInKit:@"icon_toolview_add_normal"] forState:UIControlStateNormal];
    [self.moreMediaBtn setImage:[UIImage cr_imageInKit:@"icon_toolview_add_pressed"] forState:UIControlStateHighlighted];
    [self.moreMediaBtn sizeToFit];
    
    self.recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.recordButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.recordButton.titleLabel setFont:[UIFont systemFontOfSize:14.f]];
    [self.recordButton setBackgroundImage:[[UIImage cr_imageInKit:@"icon_input_text_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(15,80,15,80) resizingMode:UIImageResizingModeStretch] forState:UIControlStateNormal];
    self.recordButton.exclusiveTouch = YES;
    [self.recordButton sizeToFit];
    
    self.inputTextBkgImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self.inputTextBkgImage setImage:[[UIImage cr_imageInKit:@"icon_input_text_bg"] resizableImageWithCapInsets:UIEdgeInsetsMake(15,80,15,80) resizingMode:UIImageResizingModeStretch]];
    
    self.inputTextView = [[ProxyTextView alloc] initWithFrame:CGRectZero];
    self.inputTextView.font = [UIFont systemFontOfSize:14.0f];
    self.inputTextView.maxNumberOfLines = _maxNumberOfInputLines?:4;
    self.inputTextView.minNumberOfLines = 1;
    self.inputTextView.textColor = [UIColor blackColor];
    self.inputTextView.backgroundColor = [UIColor clearColor];
    self.inputTextView.size = [_inputTextView intrinsicContentSize];
    self.inputTextView.textViewDelegate = self;
    self.inputTextView.returnKeyType = UIReturnKeySend;
    
    self.types = @[
      @(CRInputBarItemTypeVoice),
      @(CRInputBarItemTypeTextAndRecord),
      @(CRInputBarItemTypeEmoticon),
      @(CRInputBarItemTypeMore),
    ];
}

- (NSArray *)inputBarItemTypes {
    
    return self.types;
}

/*
** sizeToFit**
这是一个 UIView 的方法。意思是调整和移动 view 和 view 内部子视图的大小和位置。
当你想要调整当前视图,以便它使用最合适的空间的时候调用这个方法时。特定的 UIKit View 视图是根据内部需要进行尺寸调整。在特定条件下，如果 view 没有父视图，他会根据 屏幕的 bounds 来进行调整。如果你需要 view 根据父视图来调整大小，就需要将 view 添加到 父视图中。

你不可以直接对这个方法进行重写，如果你需要改变视图的默认尺寸信息，你可以重载 sizeThatFits(_:) 方法。在这个方法里面可以进行一些必要的计算并在这个方法中对计算的结果进行返回。
**/
- (CGSize)sizeThatFits:(CGSize)size {
    
    CGFloat viewHeight = 0.0f;
    
    if (self.status == CRInputStatusAudio) {
        
        viewHeight = 54;
        
    } else {
        
        //算出 TextView 的宽度
        [self adjustTextViewWidth:size.width];
        
        // TextView 自适应高度
        [self.inputTextView layoutIfNeeded];
        viewHeight = (int)self.inputTextView.frame.size.height;
        
        //得到 ToolBar 自身高度
        viewHeight = viewHeight + 2 * self.spacing + 2 * self.textViewPadding;
    }
    
    return CGSizeMake(size.width,viewHeight);
}

/// 获取文本框的宽度
/// @param width <#width description#>
- (void)adjustTextViewWidth:(CGFloat)width {
    
    CGFloat textViewWidth = 0;
    for (NSNumber *type in self.types) {
        if (type.integerValue == CRInputBarItemTypeTextAndRecord) {
            continue;
        }
        UIView *view = [self subViewForType:type.integerValue];
        textViewWidth += view.width;
    }
    textViewWidth += (self.spacing * (self.types.count + 1));
    self.inputTextView.width  = width  - textViewWidth - 2 * self.textViewPadding;
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    if ([self.types containsObject:@(CRInputBarItemTypeTextAndRecord)]) {
        //设置输入背景
        self.inputTextBkgImage.width  = self.inputTextView.width  + 2 * self.textViewPadding;
        self.inputTextBkgImage.height = self.inputTextView.height + 2 * self.textViewPadding;
    }
    
    //排列设置的按钮
    CGFloat left = 0;
    for (NSNumber *type in self.types) {
        
        UIView *view  = [self subViewForType:type.integerValue];
        if (!view.superview) {
            [self addSubview:view];
        }
        
        view.left = left + self.spacing;
        view.centerY = self.height * .5f;
        left = view.right;
    }
    
    [self adjustTextAndRecordView];
}

/// 调整输入框活着录音按钮
- (void)adjustTextAndRecordView {
    
    if ([self.types containsObject:@(CRInputBarItemTypeTextAndRecord)]) {
        
        self.inputTextView.center  = self.inputTextBkgImage.center;
        
        if (!self.inputTextView.superview) {
            
            //输入框
            [self addSubview:self.inputTextView];
        }
        
        if (!self.recordButton.superview) {
            //中间点击录音按钮
            self.recordButton.frame    = self.inputTextBkgImage.frame;
            [self addSubview:self.recordButton];
        }
    }
}

/// 切换状态
/// @param status 显示状态
- (void)updateStatus:(CRInputStatus)status {
    
    self.status = status;
    [self sizeToFit];
    
    if (status == CRInputStatusText || status == CRInputStatusMore) {
     
        self.recordButton.hidden = YES;
        self.inputTextView.hidden = NO;
        self.inputTextBkgImage.hidden = NO;
        [self updateVoiceBtnImages:YES];
        [self updateEmotAndTextBtnImages:YES];
    
    } else if (status == CRInputStatusAudio) {
        
        self.recordButton.hidden = NO;
        self.inputTextView.hidden = YES;
        self.inputTextBkgImage.hidden = YES;
        [self updateVoiceBtnImages:NO];
        [self updateEmotAndTextBtnImages:YES];
        
    } else {
        
        self.recordButton.hidden = YES;
        self.inputTextBkgImage.hidden = NO;
        self.inputTextView.hidden = NO;
        [self updateVoiceBtnImages:YES];
        [self updateEmotAndTextBtnImages:YES];
    }
}

/// 更新录音按钮样式
/// @param selected <#selected description#>
- (void)updateVoiceBtnImages:(BOOL)selected {
    
    [self.voiceButton setImage:selected?[UIImage cr_imageInKit:@"icon_toolview_voice_normal"]:[UIImage cr_imageInKit:@"icon_toolview_keyboard_normal"] forState:UIControlStateNormal];
    [self.voiceButton setImage:selected?[UIImage cr_imageInKit:@"icon_toolview_voice_pressed"]:[UIImage cr_imageInKit:@"icon_toolview_keyboard_pressed"] forState:UIControlStateHighlighted];
}

/// 更新表情按钮样式（目前并不会切换，可忽略）
/// @param selected <#selected description#>
- (void)updateEmotAndTextBtnImages:(BOOL)selected {
    
    [self.emoticonBtn setImage:selected?[UIImage cr_imageInKit:@"icon_toolview_emotion_normal"]:[UIImage cr_imageInKit:@"icon_toolview_keyboard_normal"] forState:UIControlStateNormal];
    [self.emoticonBtn setImage:selected?[UIImage cr_imageInKit:@"icon_toolview_emotion_pressed"]:[UIImage cr_imageInKit:@"icon_toolview_keyboard_pressed"] forState:UIControlStateHighlighted];
}

#pragma mark - Getter and Setter

- (UIView *)subViewForType:(CRInputBarItemType)type {
    if (!_typeViewDict) {
        _typeViewDict = @{
                  @(CRInputBarItemTypeVoice) : self.voiceButton,
                  @(CRInputBarItemTypeTextAndRecord) : self.inputTextBkgImage,
                  @(CRInputBarItemTypeEmoticon) : self.emoticonBtn,
                  @(CRInputBarItemTypeMore) : self.moreMediaBtn
                };
    }
    return _typeViewDict[@(type)];
}

- (CGFloat)spacing {
    
    return 6.f;
}

- (CGFloat)textViewPadding {
    
    return 3.f;
}

- (BOOL)showsKeyboard {
    
    return [self.inputTextView isFirstResponder];
}

- (void)setShowsKeyboard:(BOOL)showsKeyboard {
    
    if (showsKeyboard) {
        [self.inputTextView becomeFirstResponder];
    } else {
        [self.inputTextView resignFirstResponder];
    }
}

- (NSString *)contentText {
    
    return self.inputTextView.text;
}

- (void)setContentText:(NSString *)contentText {
    
    self.inputTextView.text = contentText;
}

#pragma mark - ProxyTextViewDelegate
- (BOOL)shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)replacementText {
    
    BOOL should = YES;
    if ([self.delegate respondsToSelector:@selector(shouldChangeTextInRange:replacementText:)]) {
        should = [self.delegate shouldChangeTextInRange:range replacementText:replacementText];
    }
    return should;
}

- (BOOL)textViewShouldBeginEditing:(ProxyTextView *)growingTextView {
    
    BOOL should = YES;
    if ([self.delegate respondsToSelector:@selector(textViewShouldBeginEditing)]) {
        should = [self.delegate textViewShouldBeginEditing];
    }
    return should;
}

- (void)textViewDidEndEditing:(ProxyTextView *)growingTextView {
    
    if ([self.delegate respondsToSelector:@selector(textViewDidEndEditing)]) {
        [self.delegate textViewDidEndEditing];
    }
}

- (void)textViewDidChange:(ProxyTextView *)growingTextView {
    
    if ([self.delegate respondsToSelector:@selector(textViewDidChange)]) {
        [self.delegate textViewDidChange];
    }
}

- (void)willChangeHeight:(CGFloat)height {
    
    CGFloat toolBarHeight = height + 2 * self.spacing;
    if ([self.delegate respondsToSelector:@selector(toolBarWillChangeHeight:)]) {
        [self.delegate toolBarWillChangeHeight:toolBarHeight];
    }
}

- (void)didChangeHeight:(CGFloat)height {
    
    self.height = height + 2 * self.spacing + 2 * self.textViewPadding;
    if ([self.delegate respondsToSelector:@selector(toolBarDidChangeHeight:)]) {
        [self.delegate toolBarDidChangeHeight:self.height];
    }
}

@end







#pragma mark -
#pragma mark -
#pragma mark - 文本处理

@implementation CRInputToolBar(InputText)

- (NSRange)selectedRange {
    
    return self.inputTextView.selectedRange;
}

- (void)setPlaceHolder:(NSString *)placeHolder {
    
    self.inputTextView.placeholderAttributedText = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (void)insertText:(NSString *)text {
    
    NSRange range = self.inputTextView.selectedRange;
    NSString *replaceText = [self.inputTextView.text stringByReplacingCharactersInRange:range withString:text];
    range = NSMakeRange(range.location + text.length, 0);
    self.inputTextView.text = replaceText;
    self.inputTextView.selectedRange = range;
}

- (void)deleteText:(NSRange)range {
    
    NSString *text = self.contentText;
    if (range.location + range.length <= [text length]
        && range.location != NSNotFound && range.length != 0)
    {
        NSString *newText = [text stringByReplacingCharactersInRange:range withString:@""];
        NSRange newSelectRange = NSMakeRange(range.location, 0);
        [self.inputTextView setText:newText];
        self.inputTextView.selectedRange = newSelectRange;
    }
}

@end
